package com.micro.shop.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.micro.shop.core.ErrorCode;
import com.micro.shop.core.exception.AppException;
import com.micro.shop.redis.RedisWechatApptoken;
import com.micro.shop.utils.JsonUtils;
import com.micro.shop.utils.ThreadLocalUtils;
import com.micro.shop.vo.UserTokenInfoVo;

/**    
 * @Title: BaseController.java  
 * @Description: TODO  
 * @author fanchunfeng    
 * @date 2018年4月27日 下午3:20:36  
 * @version V1.0    
 */
public abstract class BaseController {

	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private RedisWechatApptoken redisWechatApptoken;
	
	
	/**
	 * 从redis中获取用户信息
	 * @Title: getUserInfoToRedis
	 * @Return: UserInfoVo 返回值
	 */
	public UserTokenInfoVo getUserInfoToRedis(){
		String sessionid = ThreadLocalUtils.getH5token();
		return getUserInfoToRedis(sessionid);
	}
	
	
	
	/**
	 * 从redis中获取用户信息
	 * @Title: getUserInfoToRedis
	 * @Return: UserInfoVo 返回值
	 */
	public UserTokenInfoVo getUserInfoToRedis2(String sessionid){
		return getUserInfoToRedis(sessionid);
	}
	
	/**
	 * 根据token 从redis中获取用户信息
	 * @Title: getUserInfoToRedis
	 * @Return: UserInfoVo 返回值
	 */
	public UserTokenInfoVo getUserInfoToRedis(String sessionid){
		UserTokenInfoVo userInfoVo = null;
		 userInfoVo = redisWechatApptoken.getH5MemberVo(sessionid);
		//userInfoVo = JsonUtils.convertValue(json, User.class);
		if(userInfoVo == null){
			throw new AppException(ErrorCode.SystemError.SESSION_INVALID);
    	}
		//输出sessionId
		userInfoVo.setSessionId(sessionid);
		if(logger.isDebugEnabled()){
			logger.debug("当前登录用户sessionid={},userInfoVo={},threadName={}",sessionid,JsonUtils.writeValueAsString(userInfoVo),Thread.currentThread().getName());
		}
		return userInfoVo;
	}
	
	
	public Integer getUserId(){
		UserTokenInfoVo userInfo = getUserInfoToRedis();
		return userInfo==null?null:userInfo.getUserId();
	}
}
